package book.items.item26;

import java.util.Arrays;
import java.util.EmptyStackException;

public class StackG<E> {

	private E [] elements;
	private int size = 0;
	private static final int DEFAULT_INITIAL_CAPACITY = 16;
	
	// The elements array will contain only E instances from push(E)
	// this is sufficient to ensure type safety.
	@SuppressWarnings("unchecked")
	public StackG() {
		elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
	}

	public void push (E e){
		ensureCapacity();
		elements[size++] = e;
	}
	
	public E pop() {
		if(isEmpty()) {
			throw new EmptyStackException();
		}
		E e = elements[--size];
		elements[size] = null;
		return e;
	}

	public boolean isEmpty() {
		return size == 0;
	}

	private void ensureCapacity() {
		if(elements.length == size) {
			elements = Arrays.copyOf(elements, 2 * size + 1);
		}
	}
}